package xyz.yeidi.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * @Author JIP
 * @Date 2021-08-03 9:58
 * @Version 1.0
 * @Describe :  处理文件上传的servlet
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        if(!ServletFileUpload.isMultipartContent(request)){
            System.out.println("非文件上传请求");
            return;
        }
        /*创建一个DiskFileItemFactory对象，这里我们使用默认配置*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
//        /*创建一个ServletFileUpload对象*/
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

        String realPath=request.getServletContext().getRealPath("/upload");

        System.out.println("文件上传服务器地址:"+realPath);

        try {
            /*解析request对象，返回FileItem集合*/
            List<FileItem> items = servletFileUpload.parseRequest(request);

            for (FileItem item : items) {
                //判断非  普通表单项  =>二进制数据对象
                if (!item.isFormField()) {
                    //确定服务器地址
                    File path=new File(realPath);
                    if(!path.exists())
                        path.mkdir();//新建目录

                    String str=new Date().getTime()+""; //获得日期对象的毫秒值  161745672323

                    String originName=item.getName();//被上传的文件原始文件名 a.b.jpg

                    String ext=originName.substring(originName.lastIndexOf("."));//文件后缀名 jpg
                    String newName=str+ext;
                    System.out.println(realPath+"/"+newName);

                    File file=new File(realPath+"/"+newName);
                    item.write(file);//写出  另存为

                    out.print("http://localhost:8088/eleme/upload/"+newName);
                }
            }


            out.close();




        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
